#define _CRT_SECURE_NO_WARNINGS 1
class Solution {
public:
    typedef ListNode Node;
    void reverse(Node* head, Node* tail) {
        Node* cur = head;
        Node* prev = tail;
        while (cur != tail) {
            Node* next = cur->next;
            cur->next = prev;
            prev = cur;
            cur = next;
        }

    }
    ListNode* reverseKGroup(ListNode* head, int k) {
        int n = 0;
        Node* cur = head;
        while (cur) {
            n++;
            cur = cur->next;
        }
        int t = n / k;
        Node* prev = head, * dest = head;
        Node* copy = prev;
        for (int i = 0; i < t; i++) {
            int s = k;

            Node* p = nullptr;
            while (s--) {
                p = dest;
                dest = dest->next;
            }
            reverse(prev, dest);
            if (i == 0)
                head = p;
            else {

                copy->next = p;
                copy = prev;
            }
            prev = dest;
        }

        return head;
    }
};